//
//  JBPreviewCollectionCell.swift
//  joyBao
//
//  Created by Chen on 2017/7/29.
//  Copyright © 2017年 Chen. All rights reserved.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import Kingfisher
import MBProgressHUD

class JBPreviewCollectionCell: UICollectionViewCell {

    fileprivate var scrollView: UIScrollView!
    fileprivate var imageV: UIImageView!
    fileprivate var singleTapGesture: UITapGestureRecognizer!
    fileprivate var doubleTapGesture: UITapGestureRecognizer!
    fileprivate lazy var activityIndicatorView: UIActivityIndicatorView = {
        let activityV = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        activityV.center = CGPoint(x: ScreenWidth / 2.0, y: ScreenHeight / 2.0)
        return activityV
    }()

    public var singleTapCallback: (() -> Swift.Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.contentView.isExclusiveTouch = true
        self.contentView.backgroundColor = UIColor.black

        self.scrollView = UIScrollView(frame: CGRect(x: 5, y: 0, width: frame.width - 10, height: frame.height))
        self.scrollView.backgroundColor = UIColor.black
        self.scrollView.showsHorizontalScrollIndicator = false
        self.scrollView.showsVerticalScrollIndicator = false
        self.scrollView.minimumZoomScale = 1.0
        self.scrollView.maximumZoomScale = 2.0
        self.scrollView.delegate = self
        self.contentView.addSubview(self.scrollView)

        self.contentView.addSubview(self.activityIndicatorView)

        self.imageV = UIImageView()
        self.imageV.isUserInteractionEnabled = true
        self.scrollView.addSubview(self.imageV)

        weak var weakSelf = self
        self.singleTapGesture = UITapGestureRecognizer()
        self.singleTapGesture.numberOfTapsRequired = 1
        self.singleTapGesture.rx.event.subscribe { (event) in
            weakSelf?.singleTapCallback?()
        }.addDisposableTo(bag)
        self.imageV.addGestureRecognizer(self.singleTapGesture)

        self.doubleTapGesture = UITapGestureRecognizer()
        self.doubleTapGesture.numberOfTapsRequired = 2
        self.doubleTapGesture.rx.event.subscribe { (event: Event) in
            switch event {
            case .next(let tapGesture):
                if (weakSelf?.scrollView.zoomScale)! > CGFloat(1.0) {
                    weakSelf?.scrollView.setZoomScale(1.0, animated: true)
                } else {
                    let touchPoint = tapGesture.location(in: weakSelf?.imageV)
                    let newZoomScale = weakSelf?.scrollView.maximumZoomScale
                    let xSize = (weakSelf?.contentView.width)! / newZoomScale!
                    let ySize = (weakSelf?.contentView.height)! / newZoomScale!
                    weakSelf?.scrollView.zoom(to: CGRect(x: touchPoint.x - xSize / 2.0, y: touchPoint.y - ySize / 2.0, width: xSize, height: ySize), animated: true)
                }
            default: break
            }
            }.addDisposableTo(bag)
        self.imageV.addGestureRecognizer(self.doubleTapGesture)

        self.singleTapGesture.require(toFail: self.doubleTapGesture)
    }

    func updateSubViews() {
        self.imageV.origin = CGPoint.zero
        self.imageV.width = self.contentView.width

        let image = self.imageV.image!
        if image.size.width / ScreenWidth > image.size.height / ScreenHeight {
            self.imageV.height = image.size.height * ScreenWidth / image.size.width
            self.imageV.centerY = self.height / 2.0
        } else {
            let height = ScreenWidth / image.size.width * image.size.height
            self.imageV.height = height
            if height <= self.height {
                self.imageV.centerY = self.height / 2.0
            } else {//高度超过屏幕高度

            }
            self.scrollView.contentSize = CGSize(width: 0, height: height)
        }
    }

    public func updateCell(image: Any) {
        if image is UIImage {
            self.imageV.image = image as? UIImage
            self.updateSubViews()
        } else if image is String {
            if ((image as? String)?.hasPrefix("http"))! {//网络图片
                self.activityIndicatorView.startAnimating()
                weak var weakSelf = self
                self.imageV.kf.setImage(with: URL(string: (image as? String)!), placeholder: UIImage(named: ""), options: [.transition(ImageTransition.fade(0.5))], progressBlock: nil, completionHandler: { (image, error, cacheType, url) in
                    weakSelf?.activityIndicatorView.stopAnimating()
                    if error != nil {
                        MBProgressHUD.showError(message: "加载失败", view: weakSelf?.contentView)
                    } else {
                        weakSelf?.updateSubViews()
                    }
                })
            } else {
                self.imageV.image = UIImage(named: (image as? String)!)
                self.updateSubViews()
            }
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension JBPreviewCollectionCell: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self.imageV
    }

    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        let offsetX = scrollView.width > scrollView.contentSize.width ? (scrollView.width - scrollView.contentSize.width) * 0.5 : 0.0
        let offsetY = scrollView.height > scrollView.contentSize.height ? (scrollView.height - scrollView.contentSize.height) * 0.5 : 0.0
        self.imageV.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
    }
}
